package cn.xxm.scene.controller;

import cn.xxm.scene.bo.TestBO;
import cn.xxm.scene.common.base.BaseResponse;
import cn.xxm.scene.common.base.ExceptionCodeEum;
import cn.xxm.scene.exception.ExceptionCast;
import cn.xxm.scene.service.EasyService;
import cn.xxm.scene.utils.DiffDataUtils;
import cn.xxm.scene.utils.FileConfig;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.awt.geom.RectangularShape;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;

@Controller
@Slf4j
public class UploadAndCompareController {



    @Autowired
    private EasyService easyService;



    @PostMapping("/uploadAndCompare")
    @ResponseBody
    public BaseResponse excelImport(@RequestParam(value = "newFile") MultipartFile newFile, @RequestParam(value = "oldFile") MultipartFile oldFile, TestBO bo) throws IOException {
        Map diffData = new HashMap();
        InputStream newIn = null;
        InputStream oldIn = null;
       try {
           JSONObject jsonObject = easyService.testKafka("heheda");
           Properties newProperties  =   getNewFileProperties(newFile,newIn);
           Properties oldProperties  =   getNewFileProperties(oldFile,oldIn);
           //System.out.println("newProperties = " + newProperties);
           //System.out.println("oldProperties = " + oldProperties);

           for (Object key : newProperties.keySet()) {
               Object newValue = newProperties.get(key);
               Object oldValue = oldProperties.get(key);
               boolean flag = !ObjectUtils.notEqual(newValue, oldValue);
               if(!flag){
                   diffData.put(key, DiffDataUtils.getDiffData(oldValue,newValue));
               }
           }

       } catch (Exception e) {
           log.error("解析properties error",e);
       }finally {
           if(null != newIn){
               newIn.close();
           }
           if(null != oldIn){
               oldIn.close();
           }
       }
        return BaseResponse.ok(diffData);
    }

    private Properties getNewFileProperties(@RequestParam("newFile") MultipartFile newFile, InputStream newIn) throws IOException {
        Properties newProperties = new Properties();;
        if (newFile.isEmpty()) {
            ExceptionCast.cast(ExceptionCodeEum.NEW_FILE_IS_NOT_ENPTY);
        }

        //获取文件名
        String newFileName = newFile.getOriginalFilename();
        //获取文件后缀
        String type = newFileName.indexOf(".") != -1 ? newFileName.split("[.]")[1] : null;
        //文件格式判断
        if (!FileConfig.PROPERTIES_TYPES.contains(type.toLowerCase())) {
             ExceptionCast.cast(ExceptionCodeEum.FILE_TYPE_NOT_SUPPORT);
        }
        newIn = newFile.getInputStream();
        newProperties.load(newIn);
        return newProperties;
    }


    @PostMapping("/testForward")
    public String  testForward(@RequestParam(value = "newFile") MultipartFile newFile, @RequestParam(value = "oldFile") MultipartFile oldFile,  HttpServletRequest request) throws IOException {
        String params = getRequestString(request);
        JSONObject jsonObject = JSON.parseObject(params);
        String contentType = request.getContentType();
        System.out.println("contentType = " + contentType);
        String builderNumber = request.getParameter("builderNumber");
        System.out.println("builderNumber = " + builderNumber);


        if(StringUtils.isNotBlank(contentType) && contentType.contains("multipart/form-data")){
            MultipartResolver resolver = new StandardServletMultipartResolver();
            MultipartHttpServletRequest mRequest = resolver.resolveMultipart(request);
            MultiValueMap<String, MultipartFile> multiFileMap = mRequest.getMultiFileMap();
            System.out.println("multiFileMap = " + multiFileMap);


        }


        return "forward:uploadAndCompare";
    }

    private String getRequestString(HttpServletRequest request) throws IOException {

        if(null != request.getAttribute("reqeustString")){
            return (String) request.getAttribute("reqeustString");
        }
        StringBuilder requestBuffer = new StringBuilder();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "utf-8"));
        String readLine;
        while ((readLine = bufferedReader.readLine())!= null){
            requestBuffer.append(readLine);
        }

        bufferedReader.close();
        String json = requestBuffer.toString();
        request.setAttribute("requestString",json);
        return json;
    }

}